// 1、导入vue和vue-router包
import Vue from "vue";
import VueRouter from "vue-router";

import Login from '@/components/Login.vue';
import Register from '@/components/Register.vue';
import Index from '@/components/Index.vue';
import CourseSelection from '@/components/tabs/CourseSelection.vue';
import ScoreCheck from '@/components/tabs/ScoreCheck.vue';
import ClassReservation from '@/components//tabs/ClassroomReservation.vue';
import ExperimentAppointment from '@/components/tabs/ExperimentAppointment.vue';
import GraduationProject from '@/components/tabs/GraduationProject.vue';
import StatusInfo from '@/components/tabs/StatusInfo.vue';
import AcademicProcess from '@/components/tabs/AcademicProcess.vue';
// 2、调用Vue.use()函数，把VueRouter安装为Vue的插件
Vue.use(VueRouter);
// 3、创建路由的实例对象
const router = new VueRouter({
  // 注意这里路由数组是routes，而不是 routers！！
  routes: [
    { path: '/', component: Login },
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    {
      path: '/index', component: Index,
      redirect: '/index/course-selection',
      // 嵌套子路由
      children: [
        { path: 'course-selection', component: CourseSelection },
        { path: 'score-check', component: ScoreCheck },
        { path: 'classroom-reservation', component: ClassReservation },
        { path: 'experiment-appointment', component: ExperimentAppointment },
        { path: 'graduation-project', component: GraduationProject },
        { path: 'status-info', component: StatusInfo },
        { path: 'academic-process', component: AcademicProcess },

      ]
    }
  ]
});
// 定义全局前端守卫
router.beforeEach(function (to, from, next) {
  // 1、要拿到用户将要访问的hash地址
  // 2、判断hash地址是否等于 /main
  // 2.1 如果等于/main，则需要登录后才能访问成功
  // 2.2 如果不等于，则不需要登录，直接放行，调用next()
  // 3、如果访问的地址是/main，则需要读取localStorage中的token值
  // 3.1 如果有token，则放行
  // 3.2 如果没有token，则强制跳转到/login页面
  if (to.path === '/index') {
    // 要访问后台主页，需要判断是否有token
    const token = localStorage.getItem('token');
    if (token) {
      next();
    } else {
      // 未登录则强制跳转到登录页
      next('/login');
      alert('请先登录')
    }
  } else {
    // 否则直接放行
    next();
  }
})
// 4、向外共享路由的实例对象
export default router
